import { PlusOutlined } from '@ant-design/icons';
import { Button, Image, message, notification, Popconfirm, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  lists as getLists,
  update as updateApi,
  create as createApi,
  del as deleteApi,
} from '@/services/member/member';
import avatarImg from '@/assets/images/avatar.png';
import DataForm from './components/DataForm';
import { NORMAL_CODE } from '@/constants';

/**
 * 列表
 * @param param
 */
const handleList = async (param) => {
  try {
    const res = await getLists(param);
    if (res.code !== NORMAL_CODE) {
      notification['error']({
        message: '获取失败',
        description: res.msg,
      });
      return [];
    } else {
      return res.data;
    }
  } catch (error) {
    notification['error']({
      message: '获取失败',
      description: '请求异常',
    });
    return [];
  }
};
/**
 * 新增
 * @param param
 */
const handleCreate = async (param) => {
  const hide = message.loading('正在新增');
  let status = false;
  try {
    const res = await createApi(param);
    if (res.code !== NORMAL_CODE) {
      status = false;
      notification['error']({
        message: '新增失败',
        description: res.msg,
      });
    } else {
      status = true;
      notification['success']({
        message: '新增成功',
        description: res.msg,
      });
    }
  } catch (error) {
    notification['error']({
      message: '新增失败',
      description: '请求异常',
    });
    status = false;
  }
  hide();
  return status;
};
/**
 * 更新
 * @param param
 */
const handleUpdate = async (param) => {
  const hide = message.loading('正在更新');
  let status = false;
  try {
    const res = await updateApi(param);
    if (res.code !== NORMAL_CODE) {
      status = false;
      notification['error']({
        message: '更新失败',
        description: res.msg,
      });
    } else {
      status = true;
      notification['success']({
        message: '更新成功',
        description: res.msg,
      });
    }
  } catch (error) {
    notification['error']({
      message: '更新失败',
      description: '请求异常',
    });
    status = false;
  }
  hide();
  return status;
};
/**
 * 批量删除
 * @param param
 */
const handleDelete = async (param) => {
  const hide = message.loading('正在删除');
  let status = false;
  try {
    const res = await deleteApi(param);
    if (res.code !== NORMAL_CODE) {
      status = false;
      notification['error']({
        message: '删除失败',
        description: res.msg,
      });
    } else {
      status = true;
      notification['success']({
        message: '删除成功',
        description: res.msg,
      });
    }
  } catch (error) {
    notification['error']({
      message: '删除失败',
      description: '请求异常',
    });
    status = false;
  }
  hide();
  return status;
};

const TableList: React.FC = () => {
  // 表单显示隐藏
  const [formVisible, handleFormVisible] = useState(false);
  // 表单数据赋值
  const [fromData, setFromData] = useState();
  // 批量选中数据
  const [batchData, setbatchData] = useState([]);
  //表格dom
  const actionRef = useRef<ActionType>();
  //列定义
  const columns: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'username',
      width: 100,
      fixed: 'left',
    },
    {
      title: '真实姓名',
      dataIndex: 'realname',
      width: 100,
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      width: 100,
      ellipsis: true,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      width: 100,
      render: (dom) => (
        <Image width={50} height={50} src={'/admin/file/echo?id=' + dom} fallback={avatarImg} />
      ),
      hideInSearch: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 150,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 100,
      ellipsis: true,
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      width: 100,
      valueType: 'date',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 80,
      valueType: 'select',
      valueEnum: {
        0: { text: '未设置' },
        1: { text: '男' },
        2: { text: '女' },
      },
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      valueType: 'select',
      valueEnum: {
        0: { text: '未知', status: 'warning' },
        1: { text: '未激活', status: 'error' },
        2: { text: '正常', status: 'success' },
        3: { text: '冻结', status: 'error' },
      },
    },
    {
      title: '登录时间',
      dataIndex: 'login_time',
      width: 100,
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '登录ip',
      dataIndex: 'ip',
      width: 100,
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 100,
      ellipsis: true,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 150,
      valueType: 'dateRange',
      render: (text, record) => {
        return <div>{record?.created_at}</div>;
      },
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 150,
      render: (text, record, _, action) => [
        <a
          key="edit"
          onClick={() => {
            handleFormVisible(true);
            setFromData(record);
          }}
        >
          编辑
        </a>,
        <a key="delete">
          <Popconfirm
            title="是否删除?"
            onConfirm={async () => {
              const ids = record.id;
              await handleDelete({ ids });
              const arr = batchData.filter((item) => {
                return item !== record.id;
              });
              setbatchData(arr);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
            okText="是"
            cancelText="否"
          >
            删除
          </Popconfirm>
        </a>,
      ],
    },
  ];
  return (
    <PageContainer title={false}>
      <ProTable
        rowKey="id"
        scroll={{ x: 1600 }}
        rowSelection={{
          selectedRowKeys: batchData,
          onSelect: (record, selected) => {
            let arr = [];
            if (selected) {
              // 如果选中,加入selectedRowKeys
              arr = Array.from(new Set([...batchData, record.id]));
            } else {
              // 如果未选中,删除这一项数据
              arr = batchData.filter((item) => {
                return item !== record.id;
              });
            }
            setbatchData(arr);
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            let arr = [];
            const changeIds = changeRows.map((item) => item.id);
            if (selected) {
              // 如果选中,加入selectedRowKeys
              arr = Array.from(new Set([...batchData, ...changeIds]));
            } else {
              // 如果未选中,删除数据
              arr = batchData.filter((item) => {
                return changeIds.indexOf(item) < 0;
              });
            }
            setbatchData(arr);
          },
        }}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {batchData.length} 项
              <a
                style={{ marginLeft: 8 }}
                onClick={() => {
                  setbatchData([]);
                }}
              >
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a>
                <Popconfirm
                  title="是否删除?"
                  onConfirm={async () => {
                    const ids = batchData.join(',');
                    await handleDelete({ ids });
                    setbatchData([]);
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  }}
                  okText="是"
                  cancelText="否"
                >
                  批量删除
                </Popconfirm>
              </a>
            </Space>
          );
        }}
        columns={columns}
        actionRef={actionRef}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleFormVisible(true);
              setFromData({});
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const data = await handleList({
            search_page: params.current,
            search_limit: params.pageSize,
            search_username: params.username,
            search_realname: params.realname,
            search_nickname: params.nickname,
            search_mobile: params.mobile,
            search_birthday: params.birthday,
            search_status: params.status,
            search_ip: params.ip,
            search_created_begin: params.created_at ? params.created_at[0] : '',
            search_created_end: params.created_at ? params.created_at[1] : '',
          });
          return {
            data: data.list,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: data.total,
          };
        }}
      />

      <DataForm
        onSubmit={async (data) => {
          let res = {};
          data.avatar = Number(data.avatar);
          if (data.id > 0) {
            res = await handleUpdate(data);
          } else {
            res = await handleCreate(data);
          }
          if (!res) {
            return;
          }
          handleFormVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleFormVisible(false);
        }}
        formVisible={formVisible}
        values={fromData || {}}
      />
    </PageContainer>
  );
};

export default TableList;
